package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.DepartmentQuery;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("list")
    @RequiresRoles("admin")
    @RequiresPermissions(value = {"department:list","部门列表"},logical = Logical.OR)
    //逻辑判断默认与 也可设置OR
    public String list(Model model, DepartmentQuery qo){
        Subject subject = SecurityUtils.getSubject();

        //需要判断角色或者权限的时候,shiro会自动调用realm的doGetAuthorizationInfo方法
        //获取到用户数据,进行比对
        System.out.println("admin :" + subject.hasRole("admin"));
        System.out.println("employee:delete :" + subject.isPermitted("employee:delete"));

        PageInfo<Department> pageInfo = departmentService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/department/list";
    }

    @RequestMapping("saveOrUpdate")
    @RequiresPermissions(value = {"department:saveOrUpdate","部门添加/更新"},logical = Logical.OR)
    @ResponseBody
    public JsonResult saveOrUpdate(Department department){
        //int a = 1/0;
        if (department.getId() != null){
            departmentService.update(department);
        }
        else {
            departmentService.insert(department);
        }
        return new JsonResult();
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id){
        if (id != null){
            departmentService.delete(id);
        }
        return new JsonResult();
    }
}
